home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4785 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  53.3 KB

  1. Path: sun.soe.clarkson.edu!cline
  2. From: cline@sun.soe.clarkson.edu (Marshall Cline)
  3. Newsgroups: comp.lang.c++
  4. Subject: C++ FAQ: posting #1/4
  5. Followup-To: comp.lang.c++
  6. Date: 1 Feb 1996 03:20:07 GMT
  7. Organization: Paradigm Shift, Inc (technology consulting)
  8. Sender: cline@sun.soe.clarkson.edu
  9. Distribution: world
  10. Expires: +1 month
  11. Message-ID: <4epbh7$ghq@library.erc.clarkson.edu>
  12. Reply-To: cline@parashift.com (Marshall Cline)
  13. NNTP-Posting-Host: sun.soe.clarkson.edu
  14. Summary: Please read this before posting to comp.lang.c++
  15.  
  16. comp.lang.c++ Frequently Asked Questions list (with answers, fortunately).
  17. Copyright (C) 1991-96 Marshall P. Cline, Ph.D.
  18. Posting 1 of 4.
  19.  
  20. UPDATED 1/96:
  21.  * Anonymous ftp fron.soe.clarkson.edu still does not work.
  22.  * No significant changes were made this month.
  23.  
  24. UPDATED 9/95:
  25.  * Added FAQ 41 on using a variable for the first dimension of a
  26.    multi-dimensional array
  27.  * Added FAQ 123 on the code from "Numerical Recipes"
  28.  * Added section 20 ("Libraries").  It's still pretty sparse, but it's a start
  29.  * Fixed a bug in FAQ 30 (there was no variable "i")
  30.  * Added FAQ 124 on dynamic linking to avoid bloated executables
  31.  * Added FAQ 32 on trying to "reopen" cin and cout in binary mode
  32.  * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7)
  33.  
  34. UPDATED 7/95:
  35.  * Minor stuff (but not change in FTP access, below).
  36.  
  37. UPDATED 6/95:
  38.  * Corrected the mailing address where the ANSI-C++ Draft can be ordered
  39.  * Added a FAQ on floating point [Thanks to Phil Staite]
  40.  * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter]
  41.  * Added a FAQ on interrupt service routines and ptrs to member functions
  42.  * Reorganized the FAQ on allocating all objects of a certain class via 'new'
  43.  
  44. UPDATED 5/95:
  45.  * Minor cosmetic changes
  46.  
  47. UPDATED 4/95:
  48.  * Added a question on a common BC++ Windows issue
  49.  * Fixed the ftp address for NIHCL
  50.  * Added an explanation that "ARM" is short for "Annotated Reference Manual"
  51.  
  52. UPDATED 3/95:
  53.  * Added a question on "delete this"
  54.  * Added two questions on iostreams and eof
  55.  * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs
  56.  
  57. UPDATED 1/95:
  58.  * A Chinese version of this document has been produced; details below.
  59.  
  60. UPDATED 12/94:
  61.  * Added a FAQ on STL (currently #115).
  62.  * Added a FAQ on name mangling (currently #119).
  63.  * Fixed typo in FAQ that compared composition with private inheritance.
  64.  * Corrected some spelling errors.
  65.  
  66. UPDATED 11/94:
  67.  * Added differentiator between "FAQ book" and "FAQ posting"
  68.  * Other cosmetic changes
  69.  
  70. UPDATED 10/94:
  71.  * Fixed a few typos
  72.  
  73. UPDATED 9/94:
  74.  * Minor cosmetic changes
  75.  
  76. UPDATED 8/94:
  77.  * Made it up-to-date with respect to "typeid" and "dynamic_cast".
  78.  * Made it up-to-date with respect to "mutable" and "const_cast".
  79.  * Rewrote most of the answers to provide general cleanup.
  80.  * The quotation marks are now "..." rather than `...' or ``...''
  81.  * Sample code lines start with a tab; no other lines starts with a tab.
  82.  * Everything was edited; minor modifications everywhere.
  83.  
  84. ==============================================================================
  85. SECTION 1: Introduction and table of contents
  86. ==============================================================================
  87.  
  88.     DOCUMENT:    Frequently-Asked-Questions for comp.lang.c++
  89.     REVISION:    Jan 31, 1996
  90.  
  91.     POSTING!=BOOK:    This C++ FAQ posting is NOT the same as the "FAQ book".
  92.             The "FAQ book" ("C++ FAQs", Addison-Wesley, 1995) is
  93.             5x larger than this posting.  See below for more.
  94.  
  95.     AUTHOR:        Marshall P. Cline, Ph.D.
  96.             Paradigm Shift, Inc.
  97.             One Park St. / Norwood, NY  13668
  98.             voice: 315-353-6100
  99.             fax:   315-353-6110
  100.             email: cline@parashift.com
  101.  
  102.     COPYRIGHT:    Copyright (C), 1991-94 Marshall P. Cline, Ph.D.
  103.             Permission to copy all or part of this work is granted,
  104.             provided that the copies are not made or distributed
  105.             for resale (except a nominal copy fee may be charged),
  106.             and provided that the AUTHOR, COPYRIGHT, & NO WARRANTY
  107.             sections are retained verbatim and are displayed
  108.             conspicuously.  If anyone needs other permissions that
  109.             aren't covered by the above, please contact the author.
  110.  
  111.     NO WARRANTY:    THIS WORK IS PROVIDED ON AN "AS IS" BASIS.  THE AUTHOR
  112.             PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR
  113.             IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH
  114.             RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY
  115.             PARTICULAR PURPOSE.
  116.  
  117.     AVAILABILITY:    The old FTP site is no longer available.
  118.             I am searching for an alternate FTP site.
  119.             Watch this space for an FTP site next month.
  120.             Please DON'T send suggestions for ftp sites
  121.                 (my mailbox to overfloweth :-).
  122.  
  123.     SEE ALSO:    comp.lang.c FAQ appears every month in that newsgroup,
  124.             and is maintained by Steve Summit (scs@eskimo.com).
  125.  
  126.     CHINESE TRANSLATION: A Chinese translation, encoded in "Big5" code
  127.             (a 16-bit Chinese code used mostly in Taiwan)
  128.             is now available for anonymous ftp at:
  129.          ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.*
  130.  
  131. ==============================================================================
  132. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  133. ==============================================================================
  134.  
  135. Now that Addison-Wesley has published "C++ FAQs" by Cline and Lomow (1995,
  136. ISBN 0-201-58958-3), many people have asked about the relationship between the
  137. book and this posting.  Some who haven't seen the book have wondered whether
  138. the posting was equivalent to the book.  This section answers these questions.
  139.  
  140. The "FAQ book" (at bookstores starting Oct. 94) is loosely based on the same
  141. concepts as this posting.  However the FAQ book is approx five (5) times
  142. bigger than this posting, including thousands of cross references, external
  143. references, and index terms, as well as many programming examples.
  144.  
  145. ==============================================================================
  146. SUBSECTION 1B: Table of Contents
  147. ==============================================================================
  148.  
  149. ========== POSTING #1 ==========
  150.  
  151. SECTION 1: Introduction and table of contents
  152. SUBSECTION 1A: "FAQ book" versus "FAQ posting"
  153. SUBSECTION 1B: Table of Contents
  154. SUBSECTION 1C: Nomenclature and Common Abbreviations
  155.  
  156. SECTION 2: How should I post something? (READ BEFORE POSTING)
  157. Q1: Which newsgroup should I post my questions?
  158. Q2: How do I post a question about code that doesn't work correctly?
  159.  
  160. SECTION 3: Environmental/managerial issues
  161. Q3: What is OOP?  What is C++?
  162. Q4: What are some advantages of C++?
  163. Q5: Who uses C++?
  164. Q6: Are there any C++ standardization efforts underway?
  165. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  166. Q8: Is C++ backward compatible with ANSI-C?
  167. Q9: How long does it take to learn C++?
  168.  
  169. SECTION 4: Basics of the paradigm
  170. Q10: What is a class?
  171. Q11: What is an object?
  172. Q12: What is a reference?
  173. Q13: What happens if you assign to a reference?
  174. Q14: How can you reseat a reference to make it refer to a different object?
  175. Q15: When should I use references, and when should I use pointers?
  176. Q16: What's the deal with inline functions?
  177.  
  178. SECTION 5: Constructors and destructors
  179. Q17: What's the deal with constructors?
  180. Q18: How can I make a constructor call another constructor as a primitive?
  181. Q19: What's the deal with destructors?
  182.  
  183. SECTION 6: Operator overloading
  184. Q20: What's the deal with operator overloading?
  185. Q21: What operators can/cannot be overloaded?
  186. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  187.  
  188. SECTION 7: Friends
  189. Q23: What is a "friend"?
  190. Q24: Do "friends" violate encapsulation?
  191. Q25: What are some advantages/disadvantages of using friend functions?
  192. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  193. Q27: Should my class declare a member function or a friend function?
  194.  
  195. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  196. Q28: How can I provide printing for a "class Fred"?
  197. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  198. Q30: Why does my input seem to process past the end of file?
  199. Q31: Why is my program ignoring my input request after the first iteration?
  200. Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  201.  
  202. ========== POSTING #2 ==========
  203.  
  204. SECTION 9: Freestore management
  205. Q33: Does "delete p" delete the pointer "p", or the pointed-to-data, "*p"?
  206. Q34: Can I "free()" pointers allocated with "new"?  Can I "delete" pointers
  207.    alloc'd with "malloc()"?
  208. Q35: Why should I use "new" instead of trustworthy old malloc()?
  209. Q36: Why doesn't C++ have a "realloc()" along with "new" and "delete"?
  210. Q37: How do I allocate / unallocate an array of things?
  211. Q38: What if I forget the "[]" when "delete"ing array allocated via "new
  212.    Fred[n]"?
  213. Q39: Is it legal (and moral) for a member function to say "delete this"?
  214. Q40: How do I allocate multidimensional arrays using new?
  215. Q41: Does C++ have arrays whose length can be specified at run-time?
  216. Q42: How can I ensure objects of my class are always created via "new" rather
  217.    than as locals or global/static objects?
  218.  
  219. SECTION 10: Debugging and error handling
  220. Q43: How can I handle a constructor that fails?
  221. Q44: How should I handle resources if my constructors may throw exceptions?
  222.  
  223. SECTION 11: Const correctness
  224. Q45: What is "const correctness"?
  225. Q46: Should I try to get things const correct "sooner" or "later"?
  226. Q47: What is a "const member function"?
  227. Q48: What do I do if I want to update an "invisible" data member inside a
  228.    "const" member function?
  229. Q49: Does "const_cast" mean lost optimization opportunities?
  230.  
  231. SECTION 12: Inheritance
  232. Q50: Is inheritance important to C++?
  233. Q51: When would I use inheritance?
  234. Q52: How do you express inheritance in C++?
  235. Q53: Is it ok to convert a pointer from a derived class to its base class?
  236. Q54: Derived* --> Base* works ok; why doesn't Derived** --> Base** work?
  237. Q55: Does array-of-Derived is-NOT-a-kind-of array-of-Base mean arrays are
  238.    bad?
  239. SUBSECTION 12A: Inheritance -- Virtual functions
  240. Q56: What is a "virtual member function"?
  241. Q57: How can C++ achieve dynamic binding yet also static typing?
  242. Q58: Should a derived class replace ("override") a non-virtual fn from a base
  243.    class?
  244. Q59: What's the meaning of, "Warning: Derived::f(int) hides Base::f(float)"?
  245. SUBSECTION 12B: Inheritance -- Conformance
  246. Q60: Should I hide public member fns inherited from my base class?
  247. Q61: Is a "Circle" a kind-of an "Ellipse"?
  248. Q62: Are there other options to the "Circle is/isnot kind-of Ellipse"
  249.    dilemma?
  250. SUBSECTION 12C: Inheritance -- Access rules
  251. Q63: Why can't my derived class access "private" things from my base class?
  252. Q64: What's the difference between "public:", "private:", and "protected:"?
  253. Q65: How can I protect subclasses from breaking when I change internal parts?
  254. SUBSECTION 12D: Inheritance -- Constructors and destructors
  255. Q66: When my base class's constructor calls a virtual function, why doesn't my
  256.    derived class's override of that virtual function get invoked?
  257. Q67: Does a derived class destructor need to explicitly call the base
  258.    destructor?
  259. SUBSECTION 12E: Inheritance -- Private and protected inheritance
  260. Q68: How do you express "private inheritance"?
  261. Q69: How are "private inheritance" and "composition" similar?
  262. Q70: Which should I prefer: composition or private inheritance?
  263. Q71: Should I pointer-cast from a "privately" derived class to its base
  264.    class?
  265. Q72: How is protected inheritance related to private inheritance?
  266. Q73: What are the access rules with "private" and "protected" inheritance?
  267.  
  268. SECTION 13: Abstraction
  269. Q74: What's the big deal of separating interface from implementation?
  270. Q75: How do I separate interface from implementation in C++ (like Modula-2)?
  271. Q76: What is an ABC ("abstract base class")?
  272. Q77: What is a "pure virtual" member function?
  273. Q78: How can I provide printing for an entire hierarchy of classes?
  274. Q79: When should my destructor be virtual?
  275. Q80: What is a "virtual constructor"?
  276.  
  277. ========== POSTING #3 ==========
  278.  
  279. SECTION 14: Style guidelines
  280. Q81: What are some good C++ coding standards?
  281. Q82: Are coding standards necessary?  Are they sufficient?
  282. Q83: Should our organization determine coding standards from our C
  283.    experience?
  284. Q84: Should I declare locals in the middle of a fn or at the top?
  285. Q85: What source-file-name convention is best? "foo.C"? "foo.cc"? "foo.cpp"?
  286. Q86: What header-file-name convention is best? "foo.H"? "foo.hh"? "foo.hpp"?
  287. Q87: Are there any lint-like guidelines for C++?
  288.  
  289. SECTION 15: Keys for Smalltalk programmers to learn C++
  290. Q88: Why does C++'s FAQ have a section on Smalltalk? Is this
  291.    Smalltalk-bashing?
  292. Q89: What's the difference between C++ and Smalltalk?
  293. Q90: What is "static typing", and how is it similar/dissimilar to Smalltalk?
  294. Q91: Which is a better fit for C++: "static typing" or "dynamic typing"?
  295. Q92: How can you tell if you have a dynamically typed C++ class library?
  296. Q93: How do you use inheritance in C++, and is that different from Smalltalk?
  297. Q94: What are the practical consequences of diffs in Smalltalk/C++
  298.    inheritance?
  299. Q95: Do you need to learn a "pure" OOPL before you learn C++?
  300. Q96: What is the NIHCL?  Where can I get it?
  301.  
  302. SECTION 16: Reference and value semantics
  303. Q97: What is value and/or reference semantics, and which is best in C++?
  304. Q98: What is "virtual data," and how-can / why-would I use it in C++?
  305. Q99: What's the difference between virtual data and dynamic data?
  306. Q100: Should I normally use pointers to freestore allocated objects for my
  307.    data members, or should I use "composition"?
  308. Q101: What are relative costs of the 3 performance hits associated with
  309.    allocating member objects from the freestore?
  310. Q102: Are "inline virtual" member fns ever actually "inlined"?
  311. Q103: Sounds like I should never use reference semantics, right?
  312. Q104: Does the poor performance of ref semantics mean I should pass-by-value?
  313.  
  314. ========== POSTING #4 ==========
  315.  
  316. SECTION 17: Linkage-to/relationship-with C
  317. Q105: How can I call a C function "f(int,char,float)" from C++ code?
  318. Q106: How can I create a C++ function "f(int,char,float)" that is callable by
  319.    my C code?
  320. Q107: Why's the linker giving errors for C/C++ fns being called from C++/C
  321.    fns?
  322. Q108: How can I pass an object of a C++ class to/from a C function?
  323. Q109: Can my C function access data in an object of a C++ class?
  324. Q110: Why do I feel like I'm "further from the machine" in C++ as opposed to
  325.    C?
  326.  
  327. SECTION 18: Pointers to member functions
  328. Q111: Is the type of "ptr-to-member-fn" different from "ptr-to-fn"?
  329. Q112: How do I pass a ptr to member fn to a signal handler, X event callback,
  330.    etc?
  331. Q113: Why do I keep getting compile errors (type mismatch) when I try to use a
  332.    member function as an interrupt service routine? 
  333. Q114: Why am I having trouble taking the address of a C++ function?
  334. Q115: How do I declare an array of pointers to member functions?
  335.  
  336. SECTION 19: Container classes and templates
  337. Q116: How can I insert/access/change elements from a linked
  338.    list/hashtable/etc?
  339. Q117: What's the idea behind "templates"?
  340. Q118: What's the syntax / semantics for a "function template"?
  341. Q119: What's the syntax / semantics for a "class template"?
  342. Q120: What is a "parameterized type"?
  343. Q121: What is "genericity"?
  344.  
  345. SECTION 20: Libraries
  346. Q122: Where can I get a copy of "STL"?
  347. Q123: Where can I ftp the code that accompanies "Numerical Recipes"?
  348. Q124: Why is my executable so large?
  349.  
  350. SECTION 21: Nuances of particular implementations
  351. Q125: GNU C++ (g++) produces big executables for tiny programs; Why?
  352. Q126: Is there a yacc-able C++ grammar?
  353. Q127: What is C++ 1.2?  2.0?  2.1?  3.0?
  354. Q128: If name mangling was standardized, could I link code compiled with
  355.    compilers from different compiler vendors?
  356.  
  357. SECTION 22: Miscellaneous technical and environmental issues
  358. SUBSECTION 22A: Miscellaneous technical issues:
  359. Q129: Why are classes with static data members getting linker errors?
  360. Q130: What's the difference between the keywords struct and class?
  361. Q131: Why can't I overload a function by its return type?
  362. Q132: What is "persistence"?  What is a "persistent object"?
  363. Q133: Why is floating point so inaccurate?  Why doesn't this print 0.43?
  364. SUBSECTION 22B: Miscellaneous environmental issues:
  365. Q134: Is there a TeX or LaTeX macro that fixes the spacing on "C++"?
  366. Q135: Where can I access C++2LaTeX, a LaTeX pretty printer for C++ source?
  367. Q136: Where can I access "tgrind," a pretty printer for C++/C/etc source?
  368. Q137: Is there a C++-mode for GNU emacs?  If so, where can I get it?
  369. Q138: Where can I get OS-specific FAQs answered (e.g.,BC++,DOS,Windows,etc)?
  370. Q139: Why does my DOS C++ program says "Sorry: floating point code not
  371.    linked"?
  372. Q140: Why does my BC++ Windows app crash when I'm not running the BC45 IDE?
  373. ==============================================================================
  374. SUBSECTION 1C: Nomenclature and Common Abbreviations
  375. ==============================================================================
  376.  
  377. Here are a few of the abbreviations/etc used in this article:
  378.  
  379.     term    meaning
  380.     ====    ===========
  381.     fn        function
  382.     fns        functions
  383.     param    parameter
  384.     ptr        pointer, a C/C++ construct declared by:  int * p;
  385.     ref        reference, a C++ construct declared by:  int & r;
  386.     OO        object-oriented
  387.     OOP        object-oriented programming
  388.     OOPL    object-oriented programming language
  389.     method    an alternate term for "member function"
  390.  
  391. ==============================================================================
  392. SECTION 2: How should I post something? (READ BEFORE POSTING)
  393. ==============================================================================
  394.  
  395. Q1: Which newsgroup should I post my questions?
  396.  
  397. Comp.lang.c++ is the best place to discuss the C++ language itself (e.g.,
  398. C++ code design, syntax, style).  Other newsgroups exist for discussion of
  399. topics which are specific to a particular system (e.g., MS Windows or UNIX)
  400. or topics which are not directly related to the C++ language (e.g., how to
  401. use your compiler).  Here's a list of some very active newsgroups and
  402. excerpts from their Frequently Asked Questions lists.  These excerpts
  403. should give you an idea of the type of topics frequently discussed there.
  404.  
  405.   comp.os.ms-windows.programmer.tools
  406.      This group is intended for discussions about the selection and use of
  407.      tools for Windows software development.
  408.   comp.os.ms-windows.programmer.misc
  409.      This group is for all other discussions about Windows software
  410.      development.
  411.   [There's one FAQ list for all the comp.os.ms-windows.programmer.* groups]
  412.      FAQ 5.7.1.  Accessing C++ classes in a DLL
  413.      FAQ 6.1.1.  A dialog as an MDI child window [with OWL]
  414.      FAQ 6.2.1.  Disabled menu choices become enabled [with MFC]
  415.      FAQ 8.1.5.  Using STRICT with windows.h
  416.      FAQ 10.  A programmer's bibliography
  417.  
  418.   comp.os.msdos.programmer
  419.      Much of the traffic is about language products (chiefly from Borland
  420.      and Microsoft).
  421.      FAQ 301. How can I read a character without [waiting for] the Enter key?
  422.      FAQ 412. How can I read, create, change, or delete the volume label?
  423.      FAQ 504. How do I configure a COM port and use it to transmit data?
  424.      FAQ 602. How can a C program send control codes to my printer?
  425.      FAQ 606. How can I find the Microsoft mouse position and button status?
  426.      FAQ 707. How can I write a TSR (terminate-stay-resident) utility?
  427.      FAQ B0. How can I contact [Borland, Microsoft]?
  428.      [note: this FAQ is not available at rtfm.mit.edu; it is at Simtel
  429.             (e.g., oak.oakland.edu) in /pub/msdos/info/faqp*.zip and Garbo
  430.             (garbo.uwasa.fi) in /pc/doc-net/faqp*.zip]
  431.   comp.os.msdos.programmer.turbovision [Borland's character-mode framework]
  432.  
  433.   comp.unix.programmer
  434.      FAQ 4.5)  How do I use popen() to open a process for reading AND writing?
  435.      FAQ 4.6)  How do I sleep() in a C program for less than one second?
  436.  
  437.   comp.unix.solaris (covers SunOS 4.x and Solaris)
  438.      FAQ 4)  Signal Primer
  439.      FAQ 5)  Waiting for Children to Exit
  440.  
  441.   gnu.g++.help
  442.      FAQ: Where can I find a demangler?
  443.      FAQ: Getting gcc/g++ binaries for Solaris 2.x
  444.      FAQ: What documentation exists for g++ 2.x?
  445.   gnu.g++.bug [bug reports for g++ -- see the g++ docs]
  446.  
  447.   comp.lang.c
  448.      FAQ 1.10: I'm confused.  NULL is guaranteed to be 0, but the null
  449.                pointer is not?
  450.      FAQ 2.3:  So what is meant by the "equivalence of pointers and
  451.                arrays" in C?
  452.      FAQ 4.2:  [Why doesn't "printf("%d\n," i++ * i++);" work?]
  453.      FAQ 7.1:  How can I write a function that takes a variable number
  454.                of arguments? [stdarg.h or varargs.h]
  455.      FAQ 10.4: How do I declare an array of pointers to functions returning
  456.                pointers to functions returning pointers to characters?
  457.  
  458. Also check out the newsgroups comp.graphics, comp.sources.wanted,
  459. comp.programming, and comp.object (its FAQ is an excellent introduction and
  460. overview of OOP terms and concepts).  Remember that comp.std.c++ is for
  461. discussion DIRECTLY related to the evolving ANSI/ISO C++ Standard (see more
  462. below). 
  463.  
  464. There's rarely a need to crosspost a question to one of the above
  465. newsgroups and comp.lang.c++ (readers in the system-specific newsgroups
  466. aren't programming in machine language, ya know).  It's bad netiquette to
  467. crosspost widely because your problem is "really important."  If you don't
  468. get an answer in the "right" newsgroup and feel you must post here, at
  469. least consider redirecting followups back to the appropriate newsgroup.
  470.  
  471. Before posting a question to any newsgroup you should read it's FAQ list.
  472. An answer to your question is likely to be there, saving you the time of
  473. posting and saving thousands of other people around the world the time of
  474. reading your question.  People answering a FAQ are likely to be annoyed for
  475. having to answer it for the umpteenth time, or they're likely to be giving
  476. you a wrong or incomplete answer since they haven't read the FAQ either.
  477.  
  478. Frequently Asked Questions lists are available 24-hours a day via anonymous
  479. ftp (rtfm.mit.edu in /pub/usenet/comp.what.ever) or e-mail server (send a
  480. message with the line "help" to mail-server@rtfm.mit.edu).  See the article
  481. "Introduction to the *.answers newsgroups" in the newsgroup news.answers or
  482. news.announce.newusers (which contains many other must-read articles) for
  483. more information.
  484.  
  485. ==============================================================================
  486.  
  487. Q2: How do I post a question about code that doesn't work correctly?
  488.  
  489. Here's some guidelines you should follow that will help people reading
  490. comp.lang.c++ help you with an answer to your programming problem.
  491.  
  492. 1. Please read the previous FAQ to make sure that your question is about the
  493.    C++ language and not a question about programming on your system (e.g.,
  494.    graphics, printers, devices, etc.) or using your compilation
  495.    environment (e.g., "the IDE crashes when I...," "how do you turn off
  496.    warnings about...," "how do I tell it to link my libraries").  If you
  497.    want to know why your virtual CmOk() function isn't being called in
  498.    your OWL program, your question is probably more appropriate in the
  499.    Windows programming newsgroup.  If you can write a small stand-alone
  500.    program which exhibits the same undesired compiler error or behavior
  501.    as your OWL program, by all means post here in comp.lang.c++ since C++
  502.    programmers using other systems could be of help.
  503.  
  504. 2. Be descriptive in the subject line.  "C++ problem" leaves a lot to the
  505.    imagination.  "Problem new'ing a multi-dimensional array" is good.
  506.    Refrain from exclamation points, cries for HELPPP, and the once funny
  507.    "SEX SEX SEX."  If you think the problem is specific to your compiler,
  508.    you might want to mention the compiler/version in the subject line.
  509.  
  510. 3. Post code that is complete and compilable.  It's extremely difficult
  511.    to debug or reconstruct a program from a human language description.
  512.    By "complete code" I mean that any types and functions used are
  513.    declared, headers are #include'd, etc.  Please strip the code down to
  514.    the bare essentials.  We don't need a program that does something
  515.    useful at run-time, or even links.  We just need to be able to
  516.    reproduce the undesired compiler error (possibly on a different
  517.    compiler).  By "compilable code" I mean that it doesn't contain a
  518.    bunch of uncommented ellipses or line numbers at the beginning of each
  519.    line:
  520.  
  521.     14:    #include <iostream.h>
  522.     15:    class Foo { ... };  // this is annoying
  523.  
  524.    Try to organize the code into one linear program instead of making us cut
  525.    out and create header files.  Be very careful if you are typing the code
  526.    into your article -- it's often difficult to tell whether something is a
  527.    typo or the real cause of the problem.  Try using your editor's
  528.    cut&paste or "insert file" feature instead.
  529.  
  530. 4. Mention what compiler, compiler version, and system you're using.  I
  531.    know, I just said that system-specific questions should go to a
  532.    system-specific newsgroup, but compiler information is often very
  533.    useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having
  534.    lots of problems in this area").  It also warns other users of that
  535.    compiler about possible bugs.
  536.  
  537. 5. Show us the exact compiler and linker options and libraries you used
  538.    when building your program.
  539.  
  540. 6. List the exact error message and where the error was given.  "Virtual
  541.    functions don't work" doesn't tell us whether its a compile-, link-, or
  542.    run-time problem.  If the problem is at run-time, give a good
  543.    description of the behavior and any relevant information about your
  544.    system setup.
  545.  
  546. 7. Include a working e-mail address in your signature.  If the address in
  547.    given your article's "From:" line is not correct, please notify your
  548.    system administrator.  Until it is fixed, add a "Reply-To:" line to
  549.    your headers that uses your correct e-mail address.
  550.  
  551. 8. Please read the rest of this FAQ -- chances are your problem, or a
  552.    closely related problem, is discussed here.  Thank you and I hope these
  553.    suggestions help you find a solution to your problem.
  554.  
  555. ==============================================================================
  556. SECTION 3: Environmental/managerial issues
  557. ==============================================================================
  558.  
  559. Q3: What is OOP?  What is C++?
  560.  
  561. OO programming techniques are the best way we know of to develop large, complex
  562. software applications and systems.
  563.  
  564. C++ is an OO programming language.  C++ can be used both as an OOPL and simply
  565. "as a better C."  However if you use it "as a better C," don't expect to get
  566. the benefits of object-oriented programming.
  567.  
  568. OO hype: the software industry is "failing" to meet demands for large, complex
  569. software systems.  But this "failure" is actually due to our SUCCESSES: our
  570. successes have propelled users to ask for more.  Unfortunately we created a
  571. market hunger that the "structured" analysis, design and programming techniques
  572. couldn't satisfy.  This required us to create a better paradigm.
  573.  
  574. ==============================================================================
  575.  
  576. Q4: What are some advantages of C++?
  577.  
  578. GROWTH OF C++: C++ is by far the most popular OOPL.  The number of C++ users is
  579. doubling every 7.5 to 9 months.  Knowing C++ is a good resume-stuffer (but use
  580. it as an OOPL rather than just as a better C).
  581.  
  582. ENCAPSULATION: Hiding our data structures allows us to change one chunk of a
  583. system without breaking other chunks.  We provide our software chunks (we call
  584. them "classes") with safe interfaces.  Users of a chunk use its interface only.
  585. The relatively volatile "implementation" of this interface is "encapsulated"
  586. ("put into a capsule") to prevent users from becoming reliant on its temporary
  587. decisions.  In simple C, this was done by making a module's data "static", thus
  588. preventing another module from accessing our module's bits.
  589.  
  590. MULTIPLE INSTANCES: The typical C solution to encapsulation (see above) doesn't
  591. support multiple instances of the data (it's hard to make multiple instances of
  592. a module's "static" data).  If we needed multiple instances in C, we used a
  593. "struct" (but this doesn't support "encapsulation").  In C++, we can have both
  594. multiple instances and encapsulation via a "class": the "public" part of a
  595. class contains the class's interface (normally these are a special kind of
  596. function called a "member function"), and the "private" part of a class
  597. contains the class's implementation (typically these are where the bits live).
  598.  
  599. INLINE FUNCTION CALLS: In straight C, you can achieve "encapsulated structs" by
  600. putting a "void*" in a struct (the access functions use pointer casts).  This
  601. forfeits type safety, and also imposes a function call to access even trivial
  602. fields of the struct (if you allowed direct access to the struct's fields, the
  603. underlying data structure would be difficult to change since too many chunks
  604. would RELY on it being the "old" way).  Function call overhead is small, but
  605. can add up.  C++ classes allow function calls to be expanded "inline," so you
  606. have: the 1) safety of encapsulation, 2) convenience of multiple instances, 3)
  607. speed of direct access.  Furthermore the parameter types of these inline
  608. functions are checked by the compiler, an improvement over C's #define macros.
  609.  
  610. OVERLOADING OPERATORS: C++ lets you overload the standard operators on a class,
  611. which lets users exploit their intuition (e.g., "myString + yourString" might
  612. do string concatenation, "myDate++" might increment the date, "z1 * z2" might
  613. multiply complex numbers z1 and z2, "a[i]" might access the "i"th element of
  614. the "linked list" called "a", etc.  You can even have "smart pointers" that
  615. could "point" to a disk record or wherever ("x = *p" could "dereference" such a
  616. pointer, which could seek to the location on disk where p "points" and return
  617. its value").  This allows users to program in the language of the problem
  618. domain rather than in the language of the machine.
  619.  
  620. INHERITANCE: We still have just scratched the surface.  In fact, we haven't
  621. even gotten to the "object-oriented" part yet!  Suppose you have a Stack data
  622. type with operations push, pop, etc.  Suppose you want an InvertableStack,
  623. which is "just like" Stack except it also has an "invert" operation.  In "C"
  624. style, you'd have to either (1) modify the existing Stack module (trouble if
  625. "Stack" is being used by others), or (2) copy Stack into another file and text
  626. edit that file (results in lots of code duplication, another chance to break
  627. something tricky in the Stack part of InvertableStack, and especially twice as
  628. much code to maintain).  C++ provides a much cleaner solution: inheritance.
  629. You say "InvertableStack inherits everything from Stack, and InvertableStack
  630. adds the invert operation."  Done.  Stack itself remains "closed" (untouched,
  631. unmodified), and InvertableStack doesn't duplicate the code for push/pop/etc.
  632.  
  633. POLYMORPHISM AND DYNAMIC BINDING: The real power of OOP isn't just inheritance,
  634. but is the ability to pass an InvertableStack around as if it actually were a
  635. Stack.  This is "safe" since (in C++ at least) the is-a relation follows public
  636. inheritance (i.e., a InvertableStack is-a Stack that can also invert itself).
  637. Polymorphism and dynamic binding are easiest to understand from an example, so
  638. here's a "classic": a graphical draw package might deal with Circles, Squares,
  639. Rectangles, general Polygons, and Lines.  All of these are Shapes.  Most of the
  640. draw package's functions need a "Shape" parameter (as opposed to some
  641. particular kind of shape like Square).  E.g., if a Shape is picked by a mouse,
  642. the Shape might get dragged across the screen and placed into a new location.
  643. Polymorphism and dynamic binding allow the code to work correctly even if the
  644. compiler knows only that the parameter is a "Shape" without knowing the exact
  645. kind of Shape it is.  Furthermore suppose the "pick_and_drag(Shape*) function
  646. just mentioned was compiled on Tuesday, and on Wednesday you decide to add the
  647. Hexagon shape.  Strange as it sounds, pick_and_drag() will still work with
  648. Hexagons, even though the Hexagon didn't even exist when pick_and_drag() was
  649. compiled!!  (it's not really "amazing" once you understand how the C++ compiler
  650. does it -- but it's still very convenient!)
  651.  
  652. ==============================================================================
  653.  
  654. Q5: Who uses C++?
  655.  
  656. Lots and lots of companies and government sites.  Lots.
  657.  
  658. Statistically, 5 people became new C++ programmers while you read the words of
  659. the previous FAQ.
  660.  
  661. ==============================================================================
  662.  
  663. Q6: Are there any C++ standardization efforts underway?
  664.  
  665. Yes; ANSI (American) and ISO (International) groups are working closely with
  666. each other.  The ANSI-C++ committee is called "X3J16".  The ISO C++ standards
  667. group is called "WG21".  The major players in the ANSI/ISO C++ standards
  668. process includes just about everyone:
  669.  
  670. AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum.
  671. About 70 people attend each meeting.  People come from USA, UK, Japan, Germany,
  672. Sweden, Denmark, France, ... (all have "local" committees sending official
  673. representatives and conducting "local" meetings).
  674.  
  675. ==============================================================================
  676.  
  677. Q7: Where can I get a copy of the latest ANSI-C++ draft standard?
  678.  
  679. The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that is
  680. going out for public review) is available from:
  681.     http://www.cygnus.com/~mrs/wp-draft
  682.  
  683. You can also get Postscript and Adobe Acrobat versions from:
  684.     ftp://research.att.com/dist/stdc++/WP
  685.  
  686. You can get HTML and ASCII versions:
  687.     ftp://ftp.cygnus.com/pub/g++
  688.  
  689. You can also get a paper copy from:
  690.     X3 Secretariat
  691.     1250 Eye Street NW
  692.     Suite 200
  693.     Washington, DC  20005
  694.     202-626-5738
  695.  
  696. You can also order via email:
  697.     lbarra@itic.nw.dc.us (Lynn Barra)
  698.  
  699. Ask for the latest version of "Draft Proposed American National Standard for
  700. Information Systems -- Programming Language C++" which is document number
  701. CD14882.  It is typically shipped 2-day FedEx (within the continental US), so
  702. people usually get it quickly.
  703.  
  704. ==============================================================================
  705.  
  706. Q8: Is C++ backward compatible with ANSI-C?
  707.  
  708. Almost.
  709.  
  710. C++ is as close as possible to compatible with C, but no closer.  In practice,
  711. the major difference is that C++ requires prototypes, and that "f()" declares a
  712. function that takes no parameters (in C, "f()" is the same as "f(...)").  There
  713. are some very subtle differences as well, like sizeof('x') is equal to
  714. sizeof(char) in C++ but is equal to sizeof(int) in C.  Also, C++ puts structure
  715. "tags" in the same namespace as other names, whereas C requires an explicit
  716. "struct" (the "typedef struct Fred Fred" technique still works, but is
  717. redundant in C++).
  718.  
  719. ==============================================================================
  720.  
  721. Q9: How long does it take to learn C++?
  722.  
  723. Companies like Paradigm Shift, Inc. successfully teach standard industry "short
  724. courses", where we compress a university semester course into one 40hr work
  725. week.  However true mastery takes experience; there's no substitute for time.
  726. Hands-on projects are essential, since they allow concepts to "gel."
  727.  
  728. It takes 6-12 months to become proficient in C++/OOP.  Less if the developers
  729. have easy access to a "local" body of experts, more if there isn't a "good"
  730. general purpose C++ class library available.  To become one of these experts
  731. who can mentor others takes around 3 years.
  732.  
  733. Some people never make it.  You don't have a chance unless you are teachable
  734. and have personal drive.  As a bare minimum on "teachability," you have to be
  735. able to admit when you've are wrong.  As a bare minimum on "drive," you must
  736. be willing to put in some extra hours (changing the way you think [a paradigm
  737. shift] is a LOT more painful than learning a few new facts).
  738.  
  739. ==============================================================================
  740. SECTION 4: Basics of the paradigm
  741. ==============================================================================
  742.  
  743. Q10: What is a class?
  744.  
  745. The fundamental building block of OO software.
  746.  
  747. A class defines a data type, much like a struct would be in C.  In a computer
  748. science sense, a type consists of both a set of states AND a set of operations
  749. which transition between those states.  Thus "int" is a "type" because it has
  750. both a set of states AND it has operations like "add two ints" or "int*int,"
  751. etc.  In exactly the same way, a "class" provides a set of (usually public)
  752. operations, and a set of (usually non-public) data bits representing the
  753. abstract values that instances of the type can have.  From a C language
  754. perspective, a class is a struct whose members default to "private".
  755.  
  756. Think of "int" as a class that has methods called "operator++", etc.
  757.  
  758. ==============================================================================
  759.  
  760. Q11: What is an object?
  761.  
  762. A region of storage with associated semantics.
  763.  
  764. After the declaration "int i;" we say that "i is an object of type int."  In
  765. C++/OOP, "object" usually means "an instance of a class."  Thus a class defines
  766. the behavior of possibly many objects (instances).
  767.  
  768. ==============================================================================
  769.  
  770. Q12: What is a reference?
  771.  
  772. An alias (an alternate name) for an object.
  773.  
  774. References are frequently used for pass-by-reference:
  775.  
  776.     void swap(int& i, int& j)
  777.     {
  778.       int tmp = i;
  779.       i = j;
  780.       j = tmp;
  781.     }
  782.  
  783.     main()
  784.     {
  785.       int x, y;
  786.       //...
  787.       swap(x,y);
  788.     }
  789.  
  790. Here "i" and "j" are aliases for main's "x" and "y" respectively.  In other
  791. words, "i" IS "x" -- not a pointer to "x", nor a copy of "x", but "x" itself.
  792. Anything you do to "i" gets done to "x", and vise versa.
  793.  
  794. Underneath it all, references are typically implemented by pointers.  The
  795. effect is as if you used the C style pass-by-pointer, but the "&" is moved from
  796. the caller into the callee, and you eliminate all the "*"s.
  797.  
  798. ==============================================================================
  799.  
  800. Q13: What happens if you assign to a reference?
  801.  
  802. You change the referrent (the object to which the reference refers).
  803.  
  804. Remember: the reference IS the referrent, so changing the reference changes the
  805. referrent (a reference is an "Lvalue" [something that can appear on the
  806. "L"eft-hand-side of an assignment statement] for the referrent).
  807.  
  808. This insight can be pushed a bit farther by allowing references to be RETURNED.
  809. This allows function calls on the left hand side of an assignment statement,
  810. which is useful with operator overloading.
  811.  
  812. ==============================================================================
  813.  
  814. Q14: How can you reseat a reference to make it refer to a different object?
  815.  
  816. No way.
  817.  
  818. Unlike a pointer, once a reference is bound to an object, it can NOT be
  819. "reseated" to another object.  The reference itself isn't an object (it has no
  820. address; taking the address of a reference gives you the address of the
  821. referrent; remember: the reference IS its referrent).
  822.  
  823. You can't separate the reference from the referent.
  824.  
  825. ==============================================================================
  826.  
  827. Q15: When should I use references, and when should I use pointers?
  828.  
  829. Use references when you can, and pointers when you have to.
  830.  
  831. References are usually preferred over ptrs whenever you don't need "reseating"
  832. (see previous FAQ).  This usually means that references are most useful in a
  833. class's public interface.  References typically appear on the skin of an
  834. object, and pointers on the inside.
  835.  
  836. The exception to the above is where a function's parameter or return value
  837. needs a "sentinel" reference.  This is usually best done by returning/taking a
  838. pointer, and giving the NULL pointer this special significance (references
  839. should always alias objects, not a dereferenced NULL ptr).
  840.  
  841. NOTE: Old line C programmers sometimes don't like references since they provide
  842. reference semantics that isn't explicit in the caller's code.  After some C++
  843. experience, however, one quickly realizes this is a form of information hiding,
  844. which is an asset rather than a liability.  E.g., programmers should write code
  845. in the language of the problem rather than the language of the machine.
  846.  
  847. ==============================================================================
  848.  
  849. Q16: What's the deal with inline functions?
  850.  
  851. An inline function is a function whose code gets inserted into the caller's
  852. code stream.  Like a macro, inline functions improve performance by avoiding
  853. the overhead of the call itself and (especially!) by the compiler being able to
  854. optimize THROUGH the call ("procedural integration").  Unlike macros, inline
  855. functions avoid infamous macro errors by evaluating all arguments exactly once
  856. (the "call" is semantically like a regular function call, only faster).  Also
  857. unlike macros, argument types are checked, and necessary conversions are
  858. performed correctly (macros are bad for your health; don't use them unless you
  859. absolutely have to).
  860.  
  861. Beware that overuse of inline functions can cause code bloat, which can in
  862. turn have a negative performance impact in paging environments.
  863.  
  864. They are declared by using the "inline" keyword when the function is defined:
  865.  
  866.     inline void f(int i, char c) { /*...*/ }
  867.  
  868. or by including the function definition itself within a class:
  869.  
  870.     class Fred {
  871.     public:
  872.       void f(int i, char c) { /*...*/ }
  873.     };
  874.  
  875. or by defining the member function as "inline" outside the class:
  876.  
  877.     class Fred {
  878.     public:
  879.       void f(int i, char c);
  880.     };
  881.  
  882.     inline void Fred::f(int i, char c) { /*...*/ }
  883.  
  884. ==============================================================================
  885. SECTION 5: Constructors and destructors
  886. ==============================================================================
  887.  
  888. Q17: What's the deal with constructors?
  889.  
  890. Constructors build objects from dust.
  891.  
  892. Constructors are like "init functions"; they turn a pile of arbitrary bits into
  893. a living object.  Minimally they initialize internally used fields.  They may
  894. also allocate resources (memory, files, semaphores, sockets, etc).
  895.  
  896. "ctor" is a typical abbreviation for constructor.
  897.  
  898. ==============================================================================
  899.  
  900. Q18: How can I make a constructor call another constructor as a primitive?
  901.  
  902. No way.
  903.  
  904. Dragons be here: if you call another constructor, the compiler initializes a
  905. temporary local object; it does NOT initialize "this" object.  You can combine
  906. both constructors by using a default parameter, or you can share their common
  907. code in a private "init()" member function.
  908.  
  909. ==============================================================================
  910.  
  911. Q19: What's the deal with destructors?
  912.  
  913. A destructor gives an object its last rites.
  914.  
  915. Destructors are used to release any resources allocated by the object.  E.g., a
  916. Lock class might lock a semaphore, and the destructor will release that
  917. semaphore.  The most common example is when the constructor uses "new", and the
  918. destructor uses "delete".
  919.  
  920. Destructors are a "prepare to die" method.  They are often abbreviated "dtor".
  921.  
  922. ==============================================================================
  923. SECTION 6: Operator overloading
  924. ==============================================================================
  925.  
  926. Q20: What's the deal with operator overloading?
  927.  
  928. It allows users of your classes to use intuitive syntax.
  929.  
  930. Operator overloading allows C/C++ operators to have user-defined meanings on
  931. user-defined types (classes).  They're syntactic sugar for function calls:
  932.  
  933.     class Fred {
  934.     public:
  935.       //...
  936.     };
  937.  
  938.     #if 0
  939.       Fred add(Fred, Fred);        //without operator overloading
  940.       Fred mul(Fred, Fred);
  941.     #else
  942.       Fred operator+(Fred, Fred);    //with operator overloading
  943.       Fred operator*(Fred, Fred);
  944.     #endif
  945.  
  946.     Fred f(Fred a, Fred b, Fred c)
  947.     {
  948.       #if 0
  949.         return add(add(mul(a,b), mul(b,c)), mul(c,a));  //without...
  950.       #else
  951.         return a*b + b*c + c*a;                         //with...
  952.       #endif
  953.     }
  954.  
  955. ==============================================================================
  956.  
  957. Q21: What operators can/cannot be overloaded?
  958.  
  959. Most can be overloaded. The only C operators that can't be are "." and "?:"
  960. (and "sizeof," which is technically an operator).  C++ adds a few of its own
  961. operators, most of which can be overloaded except "::" and ".*".
  962.  
  963. Here's an example of the subscript operator (it returns a reference).  First
  964. withOUT operator overloading:
  965.  
  966.     class Array {
  967.     public:
  968.       #if 0
  969.         int& elem(unsigned i) { if (i>99) error(); return data[i]; }
  970.       #else
  971.         int& operator[] (unsigned i) { if (i>99) error(); return data[i]; }
  972.       #endif
  973.     private:
  974.       int data[100];
  975.     };
  976.  
  977.     main()
  978.     {
  979.       Array a;
  980.  
  981.       #if 0
  982.         a.elem(10) = 42;
  983.         a.elem(12) += a.elem(13);
  984.       #else
  985.         a[10] = 42;
  986.         a[12] += a[13];
  987.       #endif
  988.     }
  989.  
  990. ==============================================================================
  991.  
  992. Q22: Can I create a "**" operator for "to-the-power-of" operations?
  993.  
  994. Nope.
  995.  
  996. The names of, precedence of, associativity of, and arity of operators is fixed
  997. by the language.  There is no "**" operator in C++, so you cannot create one
  998. for a class type.
  999.  
  1000. If you're in doubt, consider that "x ** y" is the same as "x * (*y)" (in other
  1001. words, the compiler assumes "y" is a pointer).  Besides, operator overloading
  1002. is just syntactic sugar for function calls.  Although this particular syntactic
  1003. sugar can be very sweet, it doesn't add anything fundamental.  I suggest you
  1004. overload "pow(base,exponent)" (a double precision version is in <math.h>).
  1005.  
  1006. BTW: operator^ can work, except it has the wrong precedence and associativity.
  1007.  
  1008. ==============================================================================
  1009. SECTION 7: Friends
  1010. ==============================================================================
  1011.  
  1012. Q23: What is a "friend"?
  1013.  
  1014. Something to allow your class to grant access to another class or function.
  1015.  
  1016. Friends can be either functions or other classes.  A class grants access
  1017. privileges to its friends.  Normally a developer has political and technical
  1018. control over both the friends and methods of a class (else you need permission
  1019. from the owner of the other pieces when you want to update your class).
  1020.  
  1021. ==============================================================================
  1022.  
  1023. Q24: Do "friends" violate encapsulation?
  1024.  
  1025. If they're used properly, they actually ENHANCE encapsulation.
  1026.  
  1027. You often need to split a class in half when the two halves will have different
  1028. numbers of instances or different lifetimes.  In these cases, the two halves
  1029. usually need direct access to each other (the two halves USED to be in the same
  1030. class, so you haven't INCREASED the number of methods that have direct access
  1031. to a data structure; you've simply MOVED some of those methods).  The safest
  1032. way to implement this is to make the two halves friends of each other.
  1033.  
  1034. If you use friends like just described, you'll keep private things private.  In
  1035. a naive effort to avoid using friendship in situations like the above, many
  1036. people actually destroy encapsulation by either using public data (grotesque!),
  1037. or by making the data accessible between the halves via public get/set methods.
  1038. Having a public get and set method for a private datum is ok only when the
  1039. private datum "makes sense" from outside the class (from a user's perspective).
  1040. In many cases, these get/set methods are almost as bad as public data: they
  1041. hide (only) the NAMES of the private data members, but they don't hide the
  1042. existence of the private data members.
  1043.  
  1044. Similarly, if you use friend functions as a syntactic variant of a class's
  1045. public access functions, they don't violate encapsulation any more than a
  1046. member function violates encapsulation.  In other words, a class's friends and
  1047. members ARE the encapsulation barrier, as defined by the class itself.
  1048.  
  1049. ==============================================================================
  1050.  
  1051. Q25: What are some advantages/disadvantages of using friend functions?
  1052.  
  1053. They provide a degree of freedom in the interface design options.
  1054.  
  1055. Member fns and friend fns are equally privileged (100% vested).  The major
  1056. difference is that a friend function is called like "f(x)", while a member is
  1057. called like "x.f()".  Thus friend fns allow the class's designer to select
  1058. the syntax that is deemed most readable, which lowers maintenance costs.
  1059.  
  1060. The major disadvantage of friend functions is that they require an extra line
  1061. of code when you want dynamic binding.  To get the effect of a virtual friend,
  1062. the friend function should call a hidden (usually "protected:") virtual member
  1063. fn; e.g., "void f(Base& b) { b.do_f(); }".  Derived classes override the hidden
  1064. virtual member function ("void Derived::do_f()"), NOT the friend function.
  1065.  
  1066. ==============================================================================
  1067.  
  1068. Q26: What does it mean that "friendship is neither inherited nor transitive"?
  1069.  
  1070. The privileges of friendship aren't inherited: derived classes of a friend
  1071. aren't necessarily friends (I may declare you as my friend, but that doesn't
  1072. mean I necessarily trust your kids).  If class "Base" declares "f()" to be a
  1073. friend, "f()" doesn't have any automatic special access rights to the extra
  1074. stuff declared in derived class, "Derived."
  1075.  
  1076. The privileges of friendship aren't transitive: friends of a friend class
  1077. aren't necessarily friends of the original class (a friend of a friend isn't
  1078. necessarily a friend).  E.g., if class "Fred" declares class "Wilma" as a
  1079. friend, and class "Wilma" declares "f()" as a friend, "f()" doesn't necessarily
  1080. have any special access rights to "Fred".
  1081.  
  1082. ==============================================================================
  1083.  
  1084. Q27: Should my class declare a member function or a friend function?
  1085.  
  1086. Use a member when you can, and a friend when you have to.
  1087.  
  1088. Sometimes friends are syntactically better (e.g., in class "Fred", friend fns
  1089. allow the "Fred" param to be second, while members require it to be first).
  1090. Another good use of friend functions are the binary infix arithmetic operators
  1091. (e.g., "aComplex + aComplex" probably should be defined as a friend rather than
  1092. a member, since you want to allow "aFloat + aComplex" as well; recall members
  1093. don't allow promotion of the left hand arg, since that would change the class
  1094. of the object that is the recipient of the member function invocation).
  1095.  
  1096. In other cases, choose a member function over a friend function.
  1097.  
  1098. ==============================================================================
  1099. SECTION 8: Input/output via <iostream.h> and <stdio.h>
  1100. ==============================================================================
  1101.  
  1102. Q28: How can I provide printing for a "class Fred"?
  1103.  
  1104. Provide a friend operator<<:
  1105.  
  1106.     class Fred {
  1107.     public:
  1108.       friend ostream& operator<< (ostream& o, const Fred& fred)
  1109.         { return o << fred.i; }
  1110.       //...
  1111.     private:
  1112.       int i;    //just for illustration
  1113.     };
  1114.  
  1115. We use a friend rather than a member since the "Fred" parameter is second
  1116. rather than first.  Input is similar, but the signature is:
  1117.  
  1118.     istream& operator>> (istream& i, Fred& fred);
  1119.                                   // ^^^^^------- not "const Fred& fred"!
  1120.  
  1121. ==============================================================================
  1122.  
  1123. Q29: Why should I use <iostream.h> instead of the traditional <stdio.h>?
  1124.  
  1125. Increase type safety, reduce errors, improve performance, allow extensibility,
  1126. and provide subclassability.
  1127.  
  1128. Printf is arguably not broken, and scanf is perhaps livable despite being error
  1129. prone, however both are limited with respect to what C++ I/O can do.  C++ I/O
  1130. (using "<<" and ">>") is, relative to C (using "printf()" and "scanf()"):
  1131.  
  1132.  * Type safe -- type of object being I/O'd is known statically by the compiler,
  1133.    rather than via dynamically tested via "%" fields.
  1134.  
  1135.  * Less error prone -- redundant info increases the chance of errors.  C++ I/O
  1136.    has no redundant "%" tokens to get right.
  1137.  
  1138.  * Faster -- printf is an "interpreter" of a tiny language whose constructs
  1139.    mainly include "%" fields; it uses these fields to select the right
  1140.    formatting primitive at run-time.  C++ I/O picks these routines statically
  1141.    based on actual types of the args.  This improves performance.
  1142.  
  1143.  * Extensible -- the C++ I/O mechanism allows new user-defined types to be
  1144.    added without breaking existing code (imagine the chaos if everyone was
  1145.    simultaneously adding new incompatible "%" fields to printf and scanf?!).
  1146.  
  1147.  * Subclassable -- ostream and istream (the C++ replacements for FILE*) are
  1148.    real classes, and hence subclassable.  This means you can have other user
  1149.    defined things that look and act like streams, yet that do whatever strange
  1150.    and wonderful things you want.  You automatically get to use the zillions of
  1151.    lines of I/O code written by users you don't even know, and they don't need
  1152.    to know about your "extended stream" class.
  1153.  
  1154. ==============================================================================
  1155.  
  1156. Q30: Why does my input seem to process past the end of file?
  1157. Because the eof state is not set until after a read is attempted past the
  1158. end of file.  That is, reading the last byte from a file does not set the
  1159. eof state.
  1160.  
  1161. If your code looks like this:
  1162.  
  1163.     int i = 0;
  1164.     while (! cin.eof())  {
  1165.       cin >> x;
  1166.       ++i;
  1167.       // work with x
  1168.     }
  1169.  
  1170. Then you have an off by one error with the count i.  
  1171. What you really need is:
  1172.  
  1173.     int i;
  1174.     while (cin >> x)  {
  1175.       ++i;
  1176.       // work with x
  1177.     }
  1178.  
  1179. ==============================================================================
  1180.  
  1181. Q31: Why is my program ignoring my input request after the first iteration?
  1182. Because the numerical extractor leaves non digits behind in the input buffer.
  1183.  
  1184. If your code looks like this:
  1185.  
  1186.     char name[1000];
  1187.     int age;
  1188.  
  1189.     for (;;) {
  1190.       cout << "Name: ";
  1191.       cin >> name;
  1192.       cout << "Age: ";
  1193.       cin >> age;
  1194.     }
  1195.  
  1196. What you really want is:
  1197.  
  1198.     for (;;) {
  1199.       cout << "Name: ";
  1200.       cin >> name;
  1201.       cout << "Age: ";
  1202.       cin >> age;
  1203.       cin.ignore(INT_MAX, '\n');
  1204.     }
  1205.  
  1206. ==============================================================================
  1207.  
  1208. Q32: How can I "reopen" cin and cout in binary mode under DOS and/or OS/2?
  1209.  
  1210. Here's the typical scenario that leads to this question: Someone wants to do
  1211. binary I/O using cin and cout, but their operating system (such as DOS or
  1212. OS/2) insists on doing translations on carriagereturn-linefeed pairs.
  1213.  
  1214. Here's the answer: The predefined streams cin, cout, cerr are assumed to be
  1215. text streams, and there is no standard way to cause them to be opened in
  1216. binary mode.  Closing the streams and attempting to reopen them in binary mode
  1217. might have unexpected or undesirable results.
  1218.  
  1219. On systems where it makes a difference, the implementation might provide a way
  1220. to make them binary streams, but you would have to check the manuals to find
  1221. out.
  1222.  
  1223. --
  1224. Paradigm Shift, Inc. / P.O. Box 5108 / Potsdam, NY  13676
  1225. Technology consulting services
  1226. cline@parashift.com / Voice: 315-353-6100 / FAX: 315-353-6110
  1227.